/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.base;

import picounit.features.Feature;
import picounit.features.base.exception.InvalidFeatureClass;

import java.util.HashSet;
import java.util.Set;

class FeatureLoader {
	private final ClassPath classPath = new ClassPath();
	private final Set<String> featuresLoaded = new HashSet<String>();

	private final DefaultFeatureRegistry featureRegistry;
	private final FeatureInstantiator featureInstantiator;
	private final CodeVisitor codeVisitor;

	public FeatureLoader(String picoUnitName) {
		this.featureRegistry = new DefaultFeatureRegistry(new PicoUnitName(picoUnitName));
		this.featureInstantiator = new FeatureInstantiator(featureRegistry.resolver());
		this.codeVisitor = new FeatureCodeVisitor(featureRegistry, featuresLoaded, featureInstantiator);
	}

	public FeatureResolver loadFeatures(Class<?> ... featureClasses) {
		for (Class<?> featureClass : featureClasses) {
			if (!Feature.class.isAssignableFrom(featureClass)) {
				throw new InvalidFeatureClass(featureClass);
			}

			new ClassFeatureDescription(featureInstantiator, featureClass)
				.insertInto(featureRegistry, featuresLoaded);
		}

		classPath.visit(codeVisitor);

		featureRegistry.verify();

		return featureRegistry.resolver();
	}
}
